var modifyOrAddFlag;
//初始化数据
$(document).ready(function(){
		$('#winEdit').window('close');

		//导入
		$('#import_link').window({
			width:465,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false,
			shadow:false
		});
		$('#import_link').window('close');  //关闭窗口

		$(".import_con").delegate("#importLinkFile" ,"change", function() {
		    $("#fileName").val($('#importLinkFile').val());
		    //clearAutofillStyle();
		});
		
		$(".button_con a" ).removeClass("l-btn-plain");
		$('#cbSearch').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable: false,
		    method:'get',
		    loadFilter:function(data){
		    	var allCheck = {'id':'','name':'全部'};
		    	data.content.unshift(allCheck);
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	$('#cbSearch').combobox('setValue','');
		    }
		});
		
		$('#comboxFieldName').combobox({
			editable: false,
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    method:'get',
		    loadFilter:function(data){
		    	return data.content;
		    }
		    
		});
		$("#datagrid").datagrid({
			url : BASE_URL_FIELD_SYSTEM_SEARCH + '/findByExample' + '?v=' + Math.random(),
			method:'get',
			autoRowHeight:true,//自动行高
			singleSelect: true,//单选
			striped:true,
			nowrap:false,
			pagination:true,
			pageSize:20,
			pageList:[10,20,50,100],
			columns:[[
						{field:'',width:10,checkbox:true},
						{field:'fieldName',title:'所属领域',width:100},
						{field:'name',title:'系统名称',width:100},
						{field:'code',title:'系统编码',width:100},
						{field:'remark',title:'备注',width:300,align:'left'}
			      ]],
			loadFilter:function(data){
				return {
					total: data.totalElements,
					rows: data.content
				};
			},
			onBeforeLoad:function(param){
				param.page -= 1;
				param.size = param.rows;
				delete param.rows;
				
				param.sort = 'createTime,desc';
				var fieldId = $('#cbSearch').combobox('getValue');
				if(fieldId !=""){
					param.fieldId = fieldId;
				}
				
				var name = $('#txtSearch').val();
				if(name !=""){
					param.name = name;
				}
				
				var systemCode = $("#systemCode").val();
				if(systemCode !=""){
					param.systemCode = systemCode;
				}
			}
		});
		
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		}); 

	});
	function onAdd(){
		modifyOrAddFlag = true;
		$('#addForm')[0].reset();
		var data = $('#comboxFieldName').combobox('getData');
		$("#comboxFieldName").combobox('setValue',data[1].id);
		$("#comboxFieldName").siblings(".textbox").children(".textbox-text").val($("#comboxFieldName").combobox('getText'));
		
		$("#winEdit").window('setTitle','领域系统管理-新增');
		$('#winEdit').window('open');
	}
	//新增和修改保存
	function onSave(){
		if($("#addForm").form("validate")){
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
			
			var name = $("#name").val();
			var remark = $("#remark").val();
			var systemCode = $("#systemCode").val();
			fieldSystemInfo = {
					name:name,
					code:systemCode,
					remark:remark,
					field:BASE_URL_FIELD+'/'+$('#comboxFieldName').combobox('getValue')
					
			};
			var checkParam = {name:name,code:systemCode};
			if(!modifyOrAddFlag){
				var row = $('#datagrid').datagrid('getSelected');
				checkParam.originalId = row.id;
	 	 		if(row.name == checkParam.name && row.code==checkParam.code) // 未修改领域系统的名字，则可以直接修改
				{
	 	 			//alert("success");
	 	 			modifyFieldSystem(fieldSystemInfo);
				}
				else
				{
					$.ajax({
			    		type: "get",
			    		url: BASE_URL_FIELD_SYSTEM_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
			    		data: checkParam,
			    		contentType: "application/json",
			    		success: function(result) {
			    			if(result.isCanSave == true)
		    				{
			    				modifyFieldSystem(fieldSystemInfo);
		    				}
		    				else 
	    					{
		    					if (result.errorCode == "DUPLICATE1") 
								{
		    						$("#instance_save").linkbutton("enable");
			    					$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败，领域系统名称已存在！</p>","error");
								}
								else if(result.errorCode == "DUPLICATE2"){
									$("#instance_save").linkbutton("enable");
			    					$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败，领域系统编码已存在！</p>","error");
								}else
								{
									$("#instance_save").linkbutton("enable");
									$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败！</p>","error");
								}
	    					}
			    		},
						error: function() {
							$("#instance_save").linkbutton("enable");
							$("#instance_save .l-btn-text").text("保存");
							$.messager.alert('错误','<p>服务异常，修改领域系统信息失败，请稍后重试或联系管理员!</p>', 'error');
						}
			    	});
				}				
			}else{
				$.ajax({
		    		type: "get",
		    		url: BASE_URL_FIELD_SYSTEM_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
		    		data: checkParam,
		    		contentType: "application/json",
		    		success: function(result) {
		    			if(result.isCanSave == true)
	    				{
		    				addFieldSystem(fieldSystemInfo);
		    				
	    				}
	    				else 
    					{
	    					if (result.errorCode == "DUPLICATE1") 
							{
		    					$("#instance_save").linkbutton("enable");
		    					$("#instance_save .l-btn-text").text("保存");
								$.messager.alert('错误',"<p>新增失败，领域系统名已存在！</p>","error");
							}else if(result.errorCode == "DUPLICATE2"){
								$("#instance_save").linkbutton("enable");
		    					$("#instance_save .l-btn-text").text("保存");
								$.messager.alert('错误',"<p>新增失败，领域系统编码已存在！</p>","error");
							}else
							{
								$("#instance_save").linkbutton("enable");
								$("#instance_save .l-btn-text").text("保存");
								$.messager.alert('错误',"<p>新增失败！</p>","error");
							}
    					}
		    		},
					error: function() {
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
						$.messager.alert('错误','<p>服务异常，新增领域系统信息失败，请稍后重试或联系管理员!</p>', 'error');
					}
		    	});
			}
		}
	}
	
	function addFieldSystem(fieldSystemInfo) {
		if(!fieldSystemInfo)
		{
			var name = $("#name").val();
			var remark = $("#remark").val();
			var systemCode =$("#systemCode").val();
			fieldSystemInfo = {
					name:name,
					code:systemCode,
					remark:remark,
					field:BASE_URL_FIELD+'/'+$('#comboxFieldName').combobox('getValue')
			};
		}
		var jsonStr = JSON.stringify(fieldSystemInfo);
		$.ajax({
			url: BASE_URL_FIELD_SYSTEM + '?v=' + Math.random(),
			type:'post',
			contentType:"application/json",
			data: jsonStr,
			timeout:30000,
			success:function(){
				$.messager.alert('提示',"<p>新增成功!</p>","info");
				$('#winEdit').window('close');
				$("#datagrid").datagrid("reload", BASE_URL_FIELD_SYSTEM_SEARCH + '/findByExample' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			},
			error:function(xhr,s,err){
				$.messager.alert("错误","<p>服务异常，新增系统失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
		});
	}
	
	function modifyFieldSystem(fieldSystemInfo) {
		var row = $('#datagrid').datagrid('getSelected');
		if(!fieldSystemInfo)
		{
			var name = $("#name").val();
			var remark = $("#remark").val();
			var systemCode =$("#systemCode").val();
			fieldSystemInfo = {
					name:name,
					code:systemCode,
					remark:remark,
					field:BASE_URL_FIELD+'/'+$('#comboxFieldName').combobox('getValue')
			};
		}
		var jsonStr = JSON.stringify(fieldSystemInfo);
		$.ajax({
			url:BASE_URL_FIELD_SYSTEM_CRUD + '/' + row.id  + '?v=' + Math.random(),
			dataType:'json',
			type:'put',
			contentType:"application/json",
			data: jsonStr,
			success:function(){
				$.messager.alert('提示',"<p>修改成功!</p>","info");
				$('#winEdit').window('close');
				$("#datagrid").datagrid("reload", BASE_URL_FIELD_SYSTEM_SEARCH + '/findByExample' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			},
			error:function(xhr,s,err){
				$.messager.alert("错误","<p>服务异常，修改系统信息失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
			
			
		});
	}
	
	//修改提示
	function onUpdate(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要修改的记录</p>","warning");
		}else{
			modifyOrAddFlag = false;
			$("#comboxFieldName").combobox('setValue',row.fieldId);
			$("#comboxFieldName").siblings(".textbox").children(".textbox-text").val($("#comboxFieldName").combobox('getText'));
			$("#winEdit").window('setTitle','领域系统管理-修改');
			$('#winEdit').window('open');
			$("#name").val(row.name).validatebox('validate');
			$("#systemCode").val(row.code).validatebox('validate');
			$("#remark").val(row.remark);
			
		}
	}
	//删除
	function onDel(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要删除的记录</p>","warning");
			return;
		}
		var id = row.id;
 		var param = {fieldSystemId:id};
		$.ajax({
			url:BASE_URL_FIELD_SYSTEM_SEARCH + '/checkIsDelete' + '?v=' + Math.random(),
			dataType:'json',
			type:'get',
			data:param,
			contentType:"application/json",
			success:function(result){
				if(result.isCanDelete == true){
					
					$.messager.confirm('温馨提示','<p>你真的要删除么?</p>',function(result){
						if (result){
					 		$.ajax({
								url:BASE_URL_FIELD_SYSTEM_CRUD + '/' + row.id + '?v=' + Math.random(),
								dataType:'json',
								type:'delete',
								async:false,
								contentType:"application/json",
								timeout:30000,
								success:function(){
									$.messager.alert('提示',"<p>删除成功!</p>","info");
									$("#datagrid").datagrid("reload", BASE_URL_FIELD_SYSTEM_SEARCH + '/findByExample' + '?v=' + Math.random());
								},
								error:function(xhr,s,err){
									$.messager.alert("错误","<p>服务异常，删除领域系统失败，请重新登录或稍后再试！</p>","error");	
								}
					 		});
						}
					});
				}else{
					if(result.isCanDelete == 'EXIST_USER'){
						$.messager.alert('错误','<p>删除失败！当前操作的系统下存在用户，不允许删除！</p>','error');
					}
					if(result.isCanDelete == 'EXIST_INTERFACE'){
						$.messager.alert('错误','<p>删除失败！当前操作的系统下存在接口，不允许删除！</p>','error');
					}
					if(result.isCanDelete == 'EXIST_DBLINK'){
						$.messager.alert('错误','<p>删除失败！当前操作的系统下存在DBLink，不允许删除！</p>','error');
					}
					if(result.isCanDelete == 'EXIST_DBLINK_INTERFACE'){
						$.messager.alert('错误','<p>删除失败！当前操作的系统下存在DBLink接口，不允许删除！</p>','error');
					}
					if(result.isCanDelete == 'EXIST_KETTLE_DATASOURCE'){
						$.messager.alert('错误','<p>删除失败！当前操作的系统下存在领域系统数据源，不允许删除！</p>','error');
					}
					
				}
			},
			error:function(xhr,s,err){
				$.messager.alert("错误","<p>服务异常，删除领域系统失败，请重新登录或稍后再试！</p>","error");	
			}
	});
	}
	
	function onCancleEdit(){
		$('#winEdit').window('close');
	}
	
	function onSearch(){
		$('#datagrid').datagrid('load');
	}

	//导入
	function import_link()
	{
		$('#import_link').window('open'); 
	}
	
 	function subgo(){
 		if($("#importLinkFile").val() == "")
 		{
 			$.messager.alert("警告", "<p>请选择需要导入的.xls或.xlsx格式的文件</p>","warning");
 			return;
 		}
 		var tempArr = $("#importLinkFile").val().split(".");
 		var selFileType = tempArr[tempArr.length - 1];
 		if(selFileType != "xls" && selFileType != "xlsx")
 		{
 			$.messager.alert("提示", "<p>选择的文件格式有误，请选择.xls或.xlsx格式的文件</p>","warning");
 			return;
 		}

 		$("#buttons_inport .easyui-linkbutton").linkbutton("disable");
 		$("#buttons_inport .l-btn-text").text("正在导入...");
 		
 		//$("#import_form").submit();
 		$.ajaxFileUpload({
 	        url: '/api/importData/field/fieldSystemUpload' + "?name=" + encodeURI($("#fileName").val()), 
 	        type: 'post',
 	        secureuri: false, //一般设置为false
 	        fileElementId: 'importLinkFile', // 上传文件的id、name属性名
 	        dataType: 'text', //返回值类型，一般设置为json、application/json
 	        //data: {name:""}, //传递参数到服务器
 	        success: function(data, status){ 
 	        	//var resultObj = eval("[" + data.activeElement.innerText + "]")[0];
            	$("#fileName").val($('#importLinkFile').val());
            	
         		$("#buttons_inport .easyui-linkbutton").linkbutton("enable");
         		$("#buttons_inport .l-btn-text").text("确定导入");
         		
 	        	var resultObj = JSON.parse(data.slice(data.indexOf(">") + 1,data.indexOf("</")));
 	            if(resultObj.backValue === true)
 	            {
 	            	$('#import_link').window('close'); 
 	            	$("#datagrid").datagrid("reload", BASE_URL_FIELD_SYSTEM_SEARCH + '/findByExample' + '?v=' + Math.random());
 	            	$.messager.alert('提示',"<p>导入成功！</p>","info");
 	            }
 	            else if(resultObj.backValue === false)
 	            {
 	            	$.messager.alert('错误',"<p>导入失败!所选文件内容为空或存在异常！</p>","error");
 	            }
 	            else
 	            {
 	            	$.messager.alert('错误',"<p>导入失败！" + resultObj.backValue + "</p>", "error"); 
 	            }
 	        },
 	        error: function(data, status, e){ 
	            $("#fileName").val($('#importLinkFile').val());
         		$("#buttons_inport .easyui-linkbutton").linkbutton("enable");
         		$("#buttons_inport .l-btn-text").text("确定导入");

				$.messager.alert("错误","<p>服务异常，导入失败，请重新登录或稍后再试！</p>","error");	
 	        }
 	    });
 	}
 	
 	